<template>
  <div class="app-container">
    <!-- 分类统计卡片 -->
    <el-row :gutter="20" class="panel-group">
      <el-col :span="8">
        <div class="card total-card">
          <div class="card-body">
            <div class="card-left">
              <div class="card-title">总分类数</div>
              <div class="card-number">{{ total }}</div>
            </div>
            <div class="card-right">
              <el-icon class="icon">
                <Collection />
              </el-icon>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="card active-card">
          <div class="card-body">
            <div class="card-left">
              <div class="card-title">本月新增</div>
              <div class="card-number">{{ monthlyNew }}</div>
            </div>
            <div class="card-right">
              <el-icon class="icon">
                <TrendCharts />
              </el-icon>
            </div>
          </div>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="card usage-card">
          <div class="card-body">
            <div class="card-left">
              <div class="card-title">已关联产品</div>
              <div class="card-number">{{ usageCount }}</div>
            </div>
            <div class="card-right">
              <el-icon class="icon">
                <Link />
              </el-icon>
            </div>
          </div>
        </div>
      </el-col>
    </el-row>

    <!-- 搜索和操作栏 -->
    <el-card class="search-card">
      <div class="search-wrapper">
        <div class="search-form">
          <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="queryParams.name" placeholder="请输入分类名称" clearable prefix-icon="Search" />
            </el-form-item>
            <el-form-item label="状态" prop="status">
              <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
                <el-option label="启用" value="1" />
                <el-option label="禁用" value="0" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleQuery">
                <el-icon>
                  <Search />
                </el-icon>
                <span>搜索</span>
              </el-button>
              <el-button @click="resetQuery">
                <el-icon>
                  <Refresh />
                </el-icon>
                <span>重置</span>
              </el-button>
            </el-form-item>
          </el-form>
        </div>
        <div class="action-buttons">
          <el-button type="primary" @click="handleAdd" v-hasPermi="['farmer:category:add']">
            <el-icon>
              <Plus />
            </el-icon>
            <span>新增分类</span>
          </el-button>
        </div>
      </div>
    </el-card>

    <!-- 分类表格 -->
    <el-card class="table-card">
      <el-table v-loading="loading" :data="categoryList" row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }">
        <el-table-column label="分类名称" prop="name" width="200">
          <template #default="scope">
            <el-icon v-if="scope.row.icon" :class="scope.row.icon" />
            <span style="margin-left: 8px">{{ scope.row.name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="排序" prop="orderNum" align="center" width="80" />
        <el-table-column label="描述" prop="description" />
        <el-table-column label="状态" align="center" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.status === '1' ? 'success' : 'info'" class="status-tag" effect="light">
              {{ scope.row.status === '1' ? '启用' : '停用' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" width="300">
          <template #default="scope">
            <el-button link type="primary" icon="Plus" @click="handleAdd(scope.row)" v-if="scope.row.pId === 0">新增</el-button>
            <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button>
            <el-button link type="danger" icon="Delete" @click="handleDelete(scope.row)"
              v-if="!scope.row.children || scope.row.children.length === 0">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加/修改分类对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body destroy-on-close :close-on-click-modal="false"
      class="category-dialog">
      <el-form ref="categoryRef" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="20">
          <el-col :span="24">
            <el-form-item label="上级分类">
              <el-tree-select v-model="form.pId" :data="categoryOptions" :check-strictly=true :props="{ 
                  value: 'id', 
                  label: 'name', 
                  children: 'children'
                }" placeholder="选择上级分类" clearable class="category-tree-select" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="分类名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入分类名称" maxlength="20" show-word-limit />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="显示排序" prop="orderNum">
              <el-input-number v-model="form.orderNum" :min="0" :max="999" controls-position="right"
                class="full-width" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态">
              <el-switch
                v-model="form.status"
                :active-value="`1`"
                :inactive-value="`0`"
                active-text="启用"
                inactive-text="停用"
                class="status-switch"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="备注" prop="description">
              <el-input v-model="form.description" type="textarea" placeholder="请输入备注信息" maxlength="200" show-word-limit
                :rows="3" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel" plain>取 消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            {{ form.id ? '修改' : '新增' }}
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="ProductCategory">
import { ref, reactive, onMounted } from 'vue';
import { listCategories,addCategories, updateCategories,delCategories} from '@/api/farmer/categories'
import { ElMessage } from 'element-plus';
import { Collection, TrendCharts, Link, Plus, Picture, ArrowDown } from '@element-plus/icons-vue';

const { proxy } = getCurrentInstance();
const loading = ref(false);
const showSearch = ref(true);
const title = ref("");
const open = ref(false);
const iconPickerVisible = ref(false);
const total = ref(0);
const monthlyNew = ref(0);
const usageCount = ref(0);

// 分类列表
const categoryList = ref([]);
// 分类树选项
const categoryOptions = ref([]);



// 查询参数
const queryParams = ref({
  name: undefined,
  status: undefined
});

// 表单参数
const form = ref({
  id: undefined,
  pId: undefined,
  name: undefined,
  orderNum: 0,
  status: "0",
  description: ""
});

// 表单校验规则
const rules = {
  name: [
    { required: true, message: '请输入分类名称', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  orderNum: [
    { required: true, message: '请输入显示排序', trigger: 'blur' }
  ]
};

// 生成分类树选项
const generateCategoryOptions = (list) => {
  const children = list.map(item => {
    return {
      id: item.id,
      name: item.name,
    };
  });

  return [{
    id: 0,
    name: '主类目',
    children: children
  }];
};

// 获取状态类型
const getStatusType = (status) => {
  return status === 1 ? "success" : "info";
};

// 获取状态文本
const getStatusText = (status) => {
  return status === 1 ? "启用" : "停用";
};

/** 查询分类列表 */
const getList = async () => {
  loading.value = true;
  try {
    const res = await listCategories(queryParams.value);
    categoryList.value = res.rows;
    total.value = res.total;
    
    // 生成分类树选项
    categoryOptions.value = generateCategoryOptions(res.rows);
    
    monthlyNew.value = 1;
    usageCount.value = 15;
  } catch (error) {
    console.error('获取分类列表失败:', error);
  } finally {
    loading.value = false;
  }
};

/** 搜索按钮操作 */
const handleQuery = () => {
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  proxy.resetForm("queryRef");
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = async (row) => {
  reset();
  if (row) {
    if(row.pId === 0) {
      form.value.pId = row.id;
    } else {
      form.value.pId = row.pId;
    }
  }
  open.value = true;
  title.value = "添加分类";
};

/** 修改按钮操作 */
const handleUpdate = (row) => {
  reset();
  form.value = { ...row };
  open.value = true;
  title.value = "修改分类";
};

/** 提交按钮 */
const submitForm = async () => {
  proxy.$refs["categoryRef"].validate(async (valid) => {
    if (valid) {
      submitLoading.value = true;
      try {
        // 这里替换为实际的API调用
        if (form.value.id) {
          await updateCategories(form.value);
        } else {
          await addCategories(form.value);
        }
        ElMessage.success(form.value.id ? "修改成功" : "新增成功");
        open.value = false;
        getList();
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error("操作失败");
      } finally {
        submitLoading.value = false;
      }
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row) => {
  try {
    await proxy.$modal.confirm('是否确认删除该分类？');
    // 这里替换为实际的API调用
    await delCategories(row.id);
    getList();
    ElMessage.success("删除成功");
  } catch (error) {
    console.error('删除失败:', error);
  }
};

/** 状态修改 */
const handleStatusChange = async (row) => {
  try {
    const text = row.status === 1 ? "启用" : "停用";
    await proxy.$modal.confirm(`确认要${text}该分类吗？`);
    
    // 这里替换为实际的API调用
    await updateCategories({
      id: row.id,
      status: row.status
    });
    
    ElMessage.success(`${text}成功`);
  } catch (error) {
    // 如果失败，回滚状态
    row.status = row.status === 1 ? 0 : 1;
    console.error('状态修改失败:', error);
  }
};

/** 选择图标 */
const selected = (name) => {
  form.value.icon = name;
  iconPickerVisible.value = false;
};

// 取消按钮
const cancel = () => {
  open.value = false;
  reset();
};

// 表单重置
const reset = () => {
  form.value = {
    id: undefined,
    parentId: undefined,
    name: undefined,
    orderNum: 0,
    icon: undefined,
    status: 0,
    remark: undefined
  };
  proxy.resetForm("categoryRef");
};

// 添加提交loading状态
const submitLoading = ref(false);

onMounted(() => {
  getList();
});
</script>

<style lang="scss" scoped>
.app-container {
  padding: 20px;

  .panel-group {
    margin-bottom: 20px;

    .card {
      padding: 20px;
      border-radius: 8px;
      position: relative;
      margin-bottom: 20px;
      overflow: hidden;
      color: #fff;
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
      transition: transform 0.3s;
      
      &:hover {
        transform: translateY(-2px);
      }
      
      &.total-card { background: linear-gradient(135deg, #36d1dc, #5b86e5); }
      &.active-card { background: linear-gradient(135deg, #ff9a9e, #fad0c4); }
      &.usage-card { background: linear-gradient(135deg, #a8edea, #fed6e3); }

      .card-body {
        display: flex;
        justify-content: space-between;
        align-items: center;

        .card-left {
          .card-title {
            font-size: 14px;
            margin-bottom: 10px;
            opacity: 0.9;
          }
          .card-number {
            font-size: 28px;
            font-weight: bold;
          }
        }

        .card-right {
          .icon {
            font-size: 48px;
            opacity: 0.2;
          }
        }
      }
    }
  }

  .search-card {
    margin-bottom: 20px;
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
    background: #fff;

    :deep(.el-card__body) {
      padding: 16px 20px;
    }

    .search-wrapper {
      display: flex;
      justify-content: space-between;
      align-items: center;
      gap: 16px;

      .search-form {
        flex: 1;
        
        :deep(.el-form) {
          display: flex;
          flex-wrap: wrap;
          gap: 16px;
          margin: 0;

          .el-form-item {
            margin: 0;
            
            &__label {
              font-weight: 500;
              color: #606266;
            }

            .el-input,
            .el-select {
              width: 220px;
              
              .el-input__wrapper {
                box-shadow: 0 0 0 1px #dcdfe6;
                
                &:hover {
                  box-shadow: 0 0 0 1px #c0c4cc;
                }
                
                &.is-focus {
                  box-shadow: 0 0 0 1px #409eff;
                }
              }
            }

            .el-button {
              height: 32px;
              padding: 0 16px;
              font-weight: 500;
              transition: all 0.3s;
              display: inline-flex;
              align-items: center;
              gap: 4px;

              .el-icon {
                font-size: 14px;
              }
            }
          }
        }
      }

      .action-buttons {
        .el-button {
          height: 32px;
          padding: 0 16px;
          font-weight: 500;
          display: inline-flex;
          align-items: center;
          gap: 4px;
          border: none;
          box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);
          transition: all 0.3s;

          .el-icon {
            font-size: 14px;
          }

          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
          }
        }
      }
    }
  }

  .table-card {
    border-radius: 8px;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);

    :deep(.el-table) {
      border-radius: 8px;
      overflow: hidden;

      th {
        background-color: #f5f7fa !important;
        font-weight: 600;
        color: #303133;
      }

      .el-table__row {
        transition: all 0.3s;

        &:hover {
          background-color: #f5f7fa;
        }

        .el-button {
          padding: 4px 8px;
          
          .el-icon {
            margin-right: 4px;
          }
        }
      }
    }
  }
}

:deep(.category-dialog) {
  .el-dialog {
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);

    .el-dialog__header {
      margin: 0;
      padding: 20px 30px;
      border-bottom: 1px solid #f0f0f0;
      background: linear-gradient(to right, #f8f9fa, #ffffff);

      .el-dialog__title {
        font-size: 18px;
        font-weight: 600;
        color: #303133;
        position: relative;
        padding-left: 12px;

        &::before {
          content: '';
          position: absolute;
          left: 0;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 16px;
          background: #409eff;
          border-radius: 2px;
        }
      }
    }

    .el-dialog__body {
      padding: 30px;
    }

    .el-dialog__footer {
      padding: 20px 30px;
      border-top: 1px solid #f0f0f0;
      background: #f8f9fa;
    }

    .el-form {
      .el-form-item {
        margin-bottom: 24px;

        &:last-child {
          margin-bottom: 0;
        }

        .el-form-item__label {
          font-weight: 500;
          color: #606266;
          padding-right: 16px;
        }

        .el-form-item__content {
          .el-input__wrapper,
          .el-textarea__wrapper {
            box-shadow: 0 0 0 1px #dcdfe6;
            padding: 0 12px;
            transition: all 0.3s;

            &:hover {
              box-shadow: 0 0 0 1px #c0c4cc;
            }

            &.is-focus {
              box-shadow: 0 0 0 1px #409eff;
            }
          }

          .el-input-number {
            width: 100%;
            
            .el-input__wrapper {
              padding-right: 40px;
            }
          }

          .el-tree-select {
            width: 100%;
          }

          .el-switch {
            .el-switch__label {
              color: #909399;
              font-size: 13px;
              
              &.is-active {
                color: #409eff;
                font-weight: 500;
              }
            }

            .el-switch__core {
              border-radius: 12px;
              height: 24px;
              width: 50px;

              .el-switch__action {
                height: 20px;
                width: 20px;
                margin: 2px;
              }
            }
          }
        }
      }

      .icon-select-input {
        .el-input {
          margin-bottom: 12px;

          .el-input__wrapper {
            padding-right: 40px;
          }

          .el-icon {
            font-size: 16px;
            color: #909399;
          }
        }

        .icon-preview {
          display: flex;
          align-items: center;
          padding: 12px;
          background: linear-gradient(to right, #f8f9fa, #ffffff);
          border: 1px solid #e4e7ed;
          border-radius: 6px;
          margin-top: 12px;
          transition: all 0.3s;

          &:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 12px rgba(0, 0, 0, 0.04);
          }

          .el-icon {
            font-size: 28px;
            margin-right: 12px;
            color: #409eff;
          }

          .icon-name {
            color: #606266;
            font-size: 14px;
            font-weight: 500;
          }
        }
      }
    }

    .dialog-footer {
      text-align: right;
      padding-top: 0;

      .el-button {
        padding: 10px 24px;
        font-weight: 500;
        border-radius: 4px;
        transition: all 0.3s;

        &:hover {
          transform: translateY(-1px);
        }

        &.el-button--default {
          border-color: #dcdfe6;
          
          &:hover {
            border-color: #c0c4cc;
            color: #606266;
          }
        }

        &.el-button--primary {
          background: linear-gradient(135deg, #409eff, #3a8ee6);
          border: none;
          box-shadow: 0 2px 6px rgba(64, 158, 255, 0.2);

          &:hover {
            background: linear-gradient(135deg, #66b1ff, #409eff);
            box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
          }
        }
      }
    }
  }
}

:deep(.icon-picker-popper) {
  border-radius: 8px;
  box-shadow: 0 4px 24px rgba(0, 0, 0, 0.1);
  padding: 16px;

  .icon-list {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(80px, 1fr));
    gap: 12px;

    .icon-item {
      display: flex;
      flex-direction: column;
      align-items: center;
      padding: 12px 8px;
      border-radius: 6px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        background-color: #f5f7fa;
        transform: translateY(-1px);
      }

      .el-icon {
        font-size: 24px;
        color: #606266;
        margin-bottom: 8px;
      }

      .icon-name {
        font-size: 12px;
        color: #909399;
        text-align: center;
        word-break: break-all;
      }
    }
  }
}

.status-tag {
  min-width: 60px;
  border-radius: 4px;
  font-weight: 500;
}
</style>
